package com.gitee.hljdrl.dialog.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.gitee.hljdrl.dialog.R;


public class UIRecyclerView extends RecyclerView {

    private int mMaxHeight = 0;

    public UIRecyclerView(@NonNull Context context) {
        this(context, null);
    }

    public UIRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public UIRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }


    private void init(Context context, AttributeSet attrs) {
        // 获取自定义属性的最大高度
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.UIDialog);
        mMaxHeight = typedArray.getDimensionPixelSize(R.styleable.UIDialog_maxUIHeight, 0);
        typedArray.recycle();
    }

    public void setMaxHeight(int maxHeight) {
        this.mMaxHeight = maxHeight;
        requestLayout();  // 更新布局
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mMaxHeight != 0) {
            // 如果设置了最大高度，使用 AT_MOST 进行测量，确保高度不超过最大高度
            int newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, newHeightMeasureSpec);
        } else {
            // 如果没有设置最大高度，正常测量
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
